import React, { useState } from 'react';
import {
  Box,
  Typography,
  TextField,
  Button,
  Grid,
  Paper,
  Avatar,
  Alert,
  Snackbar,
  CircularProgress,
  useTheme,
  alpha,
  Card,
  CardContent,
  Divider,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Cancel';
import PersonIcon from '@mui/icons-material/Person';
import EmailIcon from '@mui/icons-material/Email';
import PhoneIcon from '@mui/icons-material/Phone';
import LocationOnIcon from '@mui/icons-material/LocationOn';
import BusinessIcon from '@mui/icons-material/Business';
import CalendarTodayIcon from '@mui/icons-material/CalendarToday';

interface ProfileInfoProps {
  user: any;
  onUpdate: () => void;
}

const ProfileInfo: React.FC<ProfileInfoProps> = ({ user, onUpdate }) => {
  const theme = useTheme();
  const [editMode, setEditMode] = useState(false);
  const [formData, setFormData] = useState({
    username: user.username || '',
    email: user.email || '',
    phone: user.phone || '',
    location: user.location || '',
    company: user.company || '',
    birth_date: user.birth_date ? user.birth_date.split('T')[0] : '',
    avatar: user.avatar || '',
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [successMessage, setSuccessMessage] = useState('');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('未登录，请先登录');
      }

      // 创建一个新对象，只包含实际更改的字段
      const changedData: Record<string, any> = {};
      
      // 对比原始值和新值，只添加发生变化的字段
      if (formData.username !== user.username) changedData.username = formData.username;
      if (formData.email !== user.email) changedData.email = formData.email;
      if (formData.phone !== user.phone) changedData.phone = formData.phone;
      if (formData.location !== user.location) changedData.location = formData.location;
      if (formData.avatar !== user.avatar) changedData.avatar = formData.avatar;
      
      // 特别处理company字段
      if (formData.company !== user.company) {
        console.log('单位信息变化:', {
          原始值: user.company,
          新值: formData.company
        });
        changedData.company = formData.company;
      }
      
      // 特别处理birth_date字段
      const formattedUserBirthDate = user.birth_date ? user.birth_date.split('T')[0] : '';
      if (formData.birth_date !== formattedUserBirthDate) {
        console.log('出生日期变化:', {
          原始值: formattedUserBirthDate,
          新值: formData.birth_date
        });
        changedData.birth_date = formData.birth_date;
      }

      console.log('提交的变更数据:', changedData);

      const response = await fetch('/api/profile', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(changedData)
      });

      const data = await response.json();

      if (!response.ok) {
        console.error('服务器返回错误:', data);
        throw new Error(data.error || '更新资料失败');
      }

      console.log('服务器返回的数据:', data);

      // 更新本地存储的用户信息
      const currentUser = JSON.parse(localStorage.getItem('userData') || '{}');
      const updatedUser = { ...currentUser, ...changedData };
      localStorage.setItem('userData', JSON.stringify(updatedUser));

      // 调用父组件的更新方法
      onUpdate();
      
      setSuccessMessage('个人资料更新成功');
      setSuccess(true);
      setEditMode(false);
    } catch (err) {
      console.error('更新个人资料时出错:', err);
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    // 重置表单数据为用户原始数据
    setFormData({
      username: user.username || '',
      email: user.email || '',
      phone: user.phone || '',
      location: user.location || '',
      company: user.company || '',
      birth_date: user.birth_date ? user.birth_date.split('T')[0] : '',
      avatar: user.avatar || '',
    });
    setEditMode(false);
    setError('');
  };

  const getInitials = () => {
    return user.username 
      ? user.username.charAt(0).toUpperCase() 
      : 'U';
  };

  const InfoRow = ({ icon, label, value }: { icon: React.ReactNode, label: string, value: string }) => (
    <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
      <Box sx={{ 
        mr: 2, 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center',
        color: theme.palette.primary.main,
        width: 40,
        height: 40,
        borderRadius: '50%',
        backgroundColor: alpha(theme.palette.primary.main, 0.1),
      }}>
        {icon}
      </Box>
      <Box>
        <Typography variant="caption" color="text.secondary" sx={{ display: 'block', fontSize: '0.8rem' }}>
          {label}
        </Typography>
        <Typography variant="body1" sx={{ fontWeight: 500 }}>
          {value || '未设置'}
        </Typography>
      </Box>
    </Box>
  );

  return (
    <Box>
      <Snackbar 
        open={success} 
        autoHideDuration={3000} 
        onClose={() => setSuccess(false)} 
        anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
      >
        <Alert 
          severity="success" 
          onClose={() => setSuccess(false)}
          sx={{ 
            borderRadius: '12px',
            boxShadow: '0 8px 16px rgba(0, 0, 0, 0.1)',
            '& .MuiAlert-icon': {
              alignItems: 'center',
            }
          }}
        >
          {successMessage}
        </Alert>
      </Snackbar>

      {error && (
        <Alert 
          severity="error" 
          sx={{ 
            mb: 3, 
            borderRadius: '12px',
            '& .MuiAlert-icon': {
              alignItems: 'center',
            }
          }}
        >
          {error}
        </Alert>
      )}

      {editMode ? (
        <Paper 
          elevation={0} 
          sx={{ 
            p: 3, 
            borderRadius: '16px',
            backgroundColor: alpha('#fff', 0.9),
            backdropFilter: 'blur(10px)',
            boxShadow: '0 4px 30px rgba(0, 0, 0, 0.05)',
            border: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
          }}
        >
          <form onSubmit={handleSubmit}>
            <Grid container spacing={3}>
              <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'center', mb: 2 }}>
                <Avatar 
                  src={formData.avatar} 
                  alt={formData.username}
                  sx={{ 
                    width: 100, 
                    height: 100,
                    fontSize: '2.5rem',
                    backgroundColor: theme.palette.primary.main,
                    boxShadow: '0 4px 20px rgba(0, 0, 0, 0.1)',
                    border: `3px solid ${alpha('#fff', 0.9)}`,
                  }}
                >
                  {getInitials()}
                </Avatar>
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="头像URL"
                  name="avatar"
                  value={formData.avatar}
                  onChange={handleChange}
                  placeholder="请输入头像图片的URL"
                  variant="outlined"
                  InputProps={{
                    sx: {
                      borderRadius: '12px',
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="用户名"
                  name="username"
                  value={formData.username}
                  onChange={handleChange}
                  placeholder="请输入您的用户名"
                  required
                  variant="outlined"
                  InputProps={{
                    sx: {
                      borderRadius: '12px',
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="邮箱"
                  name="email"
                  type="email"
                  value={formData.email}
                  onChange={handleChange}
                  placeholder="请输入您的邮箱"
                  required
                  variant="outlined"
                  InputProps={{
                    sx: {
                      borderRadius: '12px',
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="电话"
                  name="phone"
                  value={formData.phone}
                  onChange={handleChange}
                  placeholder="请输入您的联系电话"
                  variant="outlined"
                  InputProps={{
                    sx: {
                      borderRadius: '12px',
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="出生日期"
                  name="birth_date"
                  type="date"
                  value={formData.birth_date}
                  onChange={handleChange}
                  InputLabelProps={{ shrink: true }}
                  variant="outlined"
                  InputProps={{
                    sx: {
                      borderRadius: '12px',
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="所在地"
                  name="location"
                  value={formData.location}
                  onChange={handleChange}
                  placeholder="例如：北京市海淀区"
                  variant="outlined"
                  InputProps={{
                    sx: {
                      borderRadius: '12px',
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  fullWidth
                  label="单位"
                  name="company"
                  value={formData.company}
                  onChange={handleChange}
                  placeholder="请输入您的单位名称"
                  variant="outlined"
                  InputProps={{
                    sx: {
                      borderRadius: '12px',
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sx={{ textAlign: 'right', mt: 2 }}>
                <Button 
                  variant="outlined" 
                  color="secondary" 
                  onClick={handleCancel}
                  sx={{ 
                    mr: 2,
                    borderRadius: '12px',
                    px: 3,
                    py: 1,
                    fontWeight: 500,
                  }}
                  startIcon={<CancelIcon />}
                >
                  取消
                </Button>
                <Button 
                  type="submit" 
                  variant="contained" 
                  color="primary"
                  disabled={loading}
                  sx={{
                    borderRadius: '12px',
                    px: 3,
                    py: 1,
                    fontWeight: 500,
                    boxShadow: '0 4px 12px rgba(25, 118, 210, 0.2)',
                    '&:hover': {
                      boxShadow: '0 6px 16px rgba(25, 118, 210, 0.3)',
                      transform: 'translateY(-2px)',
                    },
                  }}
                  startIcon={loading ? <CircularProgress size={20} /> : <SaveIcon />}
                >
                  {loading ? '保存中...' : '保存资料'}
                </Button>
              </Grid>
            </Grid>
          </form>
        </Paper>
      ) : (
        <Paper
          elevation={0}
          sx={{
            p: 3,
            borderRadius: '16px',
            backgroundColor: alpha('#fff', 0.9),
            backdropFilter: 'blur(10px)',
            boxShadow: '0 4px 30px rgba(0, 0, 0, 0.05)',
            border: `1px solid ${alpha(theme.palette.divider, 0.1)}`,
          }}
        >
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
            <Typography variant="h6" sx={{ fontWeight: 600 }}>基本信息</Typography>
            <Button
              startIcon={<EditIcon />}
              variant="outlined"
              color="primary"
              onClick={() => setEditMode(true)}
              sx={{
                borderRadius: '10px',
                px: 2,
                fontWeight: 500,
              }}
            >
              编辑资料
            </Button>
          </Box>
          
          <Grid container spacing={3}>
            <Grid item xs={12} md={6}>
              <InfoRow 
                icon={<PersonIcon />} 
                label="用户名" 
                value={user.username || ''} 
              />
              <InfoRow 
                icon={<EmailIcon />} 
                label="邮箱" 
                value={user.email || ''} 
              />
              <InfoRow 
                icon={<PhoneIcon />} 
                label="电话" 
                value={user.phone || ''} 
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <InfoRow 
                icon={<LocationOnIcon />} 
                label="所在地" 
                value={user.location || ''} 
              />
              <InfoRow 
                icon={<BusinessIcon />} 
                label="单位" 
                value={user.company || ''} 
              />
              <InfoRow 
                icon={<CalendarTodayIcon />} 
                label="出生日期" 
                value={user.birth_date ? new Date(user.birth_date).toLocaleDateString('zh-CN') : ''} 
              />
            </Grid>
          </Grid>
        </Paper>
      )}
    </Box>
  );
};

export default ProfileInfo; 